import Taro, { Current } from '@tarojs/taro'
import React, { PureComponent } from 'react'
// 界面组件
import { View, Text, Button, Image } from '@tarojs/components'
import { AtFloatLayout, AtTag, AtList, AtListItem, AtInput, AtButton, AtInputNumber } from 'taro-ui'

import CTopbar from '../../../components/CTopBar/index'
import { get_current_info_api, addOrder_api, pay_api } from './service'
import './index.scss'
import GetTopBarInfo from '@/utils/GetTopBarInfo' //动态高度
/**
 * 咨询界面
 */

interface ICurrentInfo {
  address: string
  assistantPhone: string
  briefIntroduction: string
  employmentYear: number
  id: number
  isCollect: boolean
  price: number
  teacherType: number
  therapistImg: string
  therapistLabel: string
  therapistName: string
  time: number
  type: number
}

type I = {
  isOpened: boolean
  name: string
  phone: string
  orderId: number
  id: number
  current_info: ICurrentInfo
  extraText: string
  system: string
}
interface Consulting {
  state: I
}
class Consulting extends PureComponent<any> {
  constructor(props) {
    super(props)
    this.state = {
      isOpened: false,
      name: '',
      phone: '',
      orderId: 0,
      id: 0,
      current_info: {
        address: '玩儿玩儿',
        assistantPhone: '17588975773',
        briefIntroduction: '',
        employmentYear: 10,
        id: 12,
        isCollect: true,
        price: 20,
        teacherType: 2,
        therapistImg: 'http://pipe-oss.ydche.com/image/a3b633fd752249189d6cd88c09efc741微信图片_20200928145628.jpg',
        therapistLabel: '性格',
        therapistName: '李惠',
        time: 5,
        type: 1,
      },
      extraText: '获取更优质的服务', //表单内容  展示使用
      system: Taro.getStorageSync('system') || '',
    }
  }
  //WARNING! To be deprecated in React v17. Use componentDidMount instead.
  componentDidMount() {
    const { id } = Current.router?.params
    this.setState(
      {
        id: Number(id),
      },
      () => {
        this.get_current_info()
      },
    )
  }
  // 请求页面数据
  get_current_info() {
    const { id } = this.state
    get_current_info_api(id).then(({ result, data }) => {
      this.setState({
        current_info: data,
      })
    })
  }
  // 点击list打开model
  changeListItem() {
    this.setState({
      isOpened: true,
    })
  }
  // 名字双向绑定
  handleNameChange(e) {
    this.setState({
      name: e,
    })
  }
  // 手机号双向绑定
  handlePhoneChange(e) {
    this.setState({
      phone: e,
    })
  }
  // 关闭窗口
  handleClose() {
    this.setState({
      isOpened: false,
    })
  }
  // 保存表单
  async saveChange() {
    const { name, phone } = this.state
    var phoneReg = /(^1[3|4|5|7|8|9]\d{9}$)|(^09\d{8}$)/
    var nameReg = /^[\u4E00-\u9FA5]{2,4}$/
    if (!nameReg.test(name)) {
      Taro.showToast({
        title: '请输入正确姓名',
        icon: 'none',
        duration: 2000,
        mask: true,
      })
      return false
    }
    if (!phoneReg.test(phone)) {
      Taro.showToast({
        title: '请输入正确手机号码',
        icon: 'none',
        duration: 2000,
        mask: true,
      })
      return false
    }
    this.setState({
      extraText: name + '——' + phone,
      isOpened: false,
    })

    return true
  }
  // 添加订单
  async addOrder() {
    const { name, phone, current_info, id, value } = this.state
    const params = {
      price: current_info.price,
      actualPrice: current_info.price,
      commodityId: id,
      commodityType: 3,
      therapistId: current_info.id,
      appointmentName: name,
      appointmentPhone: phone,
      commodityNumber: 1, //数量
    }
    await addOrder_api(params).then(({ result, data }) => {
      this.setState({
        orderId: data,
      })
    })
  }

  // 去支付事件
  async gotoPay() {
    const { name, phone, orderId } = this.state
    const sysinfo = Taro.getSystemInfoSync()

    await this.saveChange()
    if (!name || !phone) {
      Taro.showToast({
        title: '请先填写咨询信息',
        icon: 'none',
        duration: 2000,
      })
      return
    } else {
      if (sysinfo.system.indexOf('iOS') < 0) {
        await this.addOrder()
        // 支付
        await this.pay()
      } else {
        Taro.showModal({
          title: '提示',
          content: '十分抱歉，由于相关规范，您暂时无法测试',
          success: function (res) {
            if (res.confirm) {
              console.log('用户点击确定')
            } else if (res.cancel) {
              console.log('用户点击取消')
            }
          },
        })
      }
    }
  }

  // 支付接口请求
  pay() {
    const { current_info, orderId } = this.state
    const status = 0 //预约成功状态  0：成功 1：失败
    pay_api(orderId).then(({ result, data }) => {
      if (result === 1999) {
        Taro.requestPayment({
          timeStamp: data.timeStamp,
          nonceStr: data.nonceStr,
          package: data.package,
          signType: data.signType,
          paySign: data.paySign,
          success: function (res) {
            Taro.showLoading({
              title: '请稍等',
              mask: true,
              success: () => {
                setTimeout(() => {
                  Taro.redirectTo({
                    url:
                      '/pages/Consulting/AppointmentSuccessful/index?consultTeacherType=' +
                      current_info.teacherType +
                      '&therapistName=' +
                      current_info.therapistName +
                      '&status=' +
                      status,
                  })
                  Taro.hideLoading()
                }, 2000)
              },
            })
          },
          fail: function (res) {
            console.log(res)
          },
        })
      }
    })
  }

  render() {
    const consultTeacherTypeArr = ['', '高级', '资深', '主任', '专家']
    const { isOpened = false, current_info, extraText, system } = this.state
    return (
      <View style={{ paddingTop: `${GetTopBarInfo().TopBarHeight}px` }}>
        <View className='header'>
          <CTopbar title='预约咨询' showBack></CTopbar>
        </View>
        <View className='content'>
          <View className='card'>
            <Image src={current_info.therapistImg} />
            <View className='cardRight'>
              <View className='card_info'>
                <View>{current_info.therapistName}</View>
                <View>国家{consultTeacherTypeArr[current_info.teacherType]}心理咨询师</View>
                <View>
                  <AtTag circle>标签</AtTag>
                  <AtTag circle>标签</AtTag>
                  <AtTag circle>标签</AtTag>
                </View>
              </View>
              <View className='card_price'>
                {system.indexOf('iOS') < 0 ? '￥' + current_info.price / current_info.time + '分钟' : '免费'}
              </View>
            </View>
          </View>

          <View className='strip'>
            <AtList>
              <AtListItem arrow='right' title='资讯信息' extraText={extraText} onClick={this.changeListItem.bind(this)} />
            </AtList>
          </View>

          <View className='footer'>
            <View className='footer_content'>
              <View className='footer_l'>
                合计金额：
                <Text className='price_text'>
                  {system.indexOf('iOS') < 0 ? (current_info.price ? current_info.price : '免费') : '免费'}
                </Text>
              </View>
              <View className='footer_r'>
                <Text className='footer_r_text' onClick={this.gotoPay.bind(this)}>
                  去支付
                </Text>
              </View>
            </View>
          </View>
        </View>

        <AtFloatLayout isOpened={isOpened} title='这是个标题' onClose={this.handleClose.bind(this)}>
          <View className='input_wrapper'>
            <AtInput
              required
              name='name'
              title='姓名'
              type='text'
              placeholder='请输入咨询人姓名'
              value={this.state.name}
              onChange={this.handleNameChange.bind(this)}
            />
            <AtInput
              required
              name='phone'
              title='手机号'
              type='text'
              placeholder='请输入咨询电话'
              value={this.state.phone}
              onChange={this.handlePhoneChange.bind(this)}
            />
            <View className='save' style={{ margin: '30px 0' }}>
              <AtButton circle type='primary' onClick={this.saveChange.bind(this)}>
                保存
              </AtButton>
            </View>
          </View>
        </AtFloatLayout>
      </View>
    )
  }
}

export default Consulting
